/**
 * 
 */
package com.antilia.infomaresme.data.dao.mock;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.antilia.infomaresme.data.dao.interfaces.IImageService;
import com.antilia.infomaresme.data.dataobjects.ImageDetail;
import com.antilia.infomaresme.data.dataobjects.Item;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

/**
 * @author Ernesto
 *
 */
public class MockImageService implements IImageService {

	private static final long serialVersionUID = 1L;

	private static String[] FILES = new String[]{
			"07-2011-156.jpg",
			"07-2011-157.jpg",
			"07-2011-158.jpg",
			"07-2011-159.jpg",
			"07-2011-162.jpg",
		};
	
	
	private static List<ImageDetail> DETAILS = new ArrayList<ImageDetail>();
	
	private static Map<String, ImageDetail> THUMBNAILS = new HashMap<String,ImageDetail>();
	
	static {
		for(String file: FILES) {
			ImageDetail detail = new ImageDetail();
			detail.setBlobId(file);
			try {
				detail.setBytes(FileUtils.bytes(MockImageService.class.getResourceAsStream(file)));
			} catch (IOException e) {
				e.printStackTrace();
			}
			detail.setTitle(file);
			detail.setContentType("image/jpg");
			DETAILS.add(detail);
		}
	}
	
	private static final IImageService SERVICE = new MockImageService();
	
	/**
	 * 
	 */
	private MockImageService() {
		// TODO Auto-generated constructor stub
	}

	/* (non-Javadoc)
	 * @see com.antilia.infomaresme.data.dao.interfaces.ImageService#getImageDetails(com.antilia.infomaresme.data.dataobjects.Item)
	 */
	@Override
	public List<ImageDetail> getImageDetails(Item item) {
		return DETAILS;
	}
	
	@Override
	public ImageDetail resizeImage(ImageDetail imageDetail, int width, int height) {
		ImageDetail thumbNail = THUMBNAILS.get(imageDetail.getBlobId());
		if(thumbNail != null) {
			return thumbNail;			
		}
		ImagesService imagesService = ImagesServiceFactory.getImagesService();
		Image oldImage = ImagesServiceFactory.makeImage(imageDetail.getBytes());
		Transform resize = ImagesServiceFactory.makeResize(width, height);
		Image newImage = imagesService.applyTransform(resize, oldImage);
		byte[] newImageData = newImage.getImageData();
		ImageDetail nImage = new ImageDetail();
		nImage.setTitle(imageDetail.getTitle());
		nImage.setBytes(newImageData);
		nImage.setContentType(imageDetail.getContentType());
		THUMBNAILS.put(imageDetail.getBlobId(), nImage);
		return nImage;
	}

	@Override
	public ImageDetail storeImage(byte[] image, String contentType) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public static IImageService getService() {
		return SERVICE;
	}

}
